import React, { useState,useEffect, useTransition } from 'react'
import {Button, Card,Modal,Form,message,Row,Col,Input,Upload,Select,Tooltip} from 'antd'
import { useNavigate } from 'react-router-dom';
import useCacheAlive from '@/hooks/useCacheAlive'
import MemoTable from '@/components/MemoTable';
import { useTranslation } from 'react-i18next';
import { UploadOutlined } from '@ant-design/icons';  
import {download} from '@/utils/request';
import { list,del,add,edit} from "@/api/modules/inci";
import { upload } from "@/api/modules/common";
import { ProFormColumnsType } from '@ant-design/pro-components'
import { getInfo } from "@/api/login/ssoLogin";

const inciList = () => {
  const navigate = useNavigate();
  const { t } = useTranslation()
  const [isModalVisible, setIsModalVisible] = useState(false); 
  const [Title, setTitle] = useState("")  
  const [form] = Form.useForm();  
  const [fileList, setFileList] = useState([]); 
  const [filename, setFilename] = useState(""); 
  const [isView, SetisView] = useState(false)
  const [onReloadNum,setOnReloadNum] = useState(null)
  const [viewStatus, setViewStatus] = useState(false); // 加载状态 


  // 使用useEffect在组件挂载时获取数据  
  useEffect(() => {  
    getInfo().then(res=>{
      console.log(res,'res')
      let data = res.data
      data.roles.forEach((item)=>{
        if(item == "Formulator"){
          setViewStatus(true)
        }
      })
    }) 

  }, []);

  const formColumns:ProFormColumnsType[] = [{
    title: t('INCI'),
    dataIndex: 'search',
    valueType: 'text', 
  }]

  const columns: any = [
    {
      title: t('inci.serial'),
      dataIndex: 'serial',
      key: 'serial',
      width: 60,
      fixed:'left',
    },
    {
      title: t('inci.inciCn'),
      dataIndex: 'inciCn',
      width: 100,
      key: 'inciCn',
      ellipsis: {
        showTitle: false,
      },
      render: (inciCn) => (
        <Tooltip placement="topLeft" title={inciCn}>
          {inciCn}
        </Tooltip>
      ),
    },
    {
      title: t('inci.inciUs'),
      dataIndex: 'inciUs',
      width: 120,
      key: 'inciUs',
      ellipsis: {
        showTitle: false,
      },
      render: (inciUs) => (
        <Tooltip placement="topLeft" title={inciUs}>
          {inciUs}
        </Tooltip>
      ),
    },
    {
      title: t('inci.comment2'),
      dataIndex: 'comment2',
      width: 80,
      key: 'comment2',
      ellipsis: {
        showTitle: false,
      },
      render: (comment2) => (
        <Tooltip placement="topLeft" title={comment2}>
          {comment2}
        </Tooltip>
      ),
    },
    {
      title: t('inci.maxDoseLeaveon'),
      dataIndex: 'maxDoseLeaveon',
      key: 'maxDoseLeaveon',
      ellipsis: {
        showTitle: false,
      },
      render: (maxDoseLeaveon) => (
        <Tooltip placement="topLeft" title={maxDoseLeaveon}>
          {maxDoseLeaveon}
        </Tooltip>
      ),
    },
 
    {
      title: t('inci.maxDoseRinseoff'),
      dataIndex: 'maxDoseRinseoff',
      key: 'maxDoseRinseoff',
      ellipsis: {
        showTitle: false,
      },
      render: (maxDoseRinseoff) => (
        <Tooltip placement="topLeft" title={maxDoseRinseoff}>
          {maxDoseRinseoff}
        </Tooltip>
      ),
    },
    {
      title: t('inci.comment1'),
      dataIndex: 'comment1',
      key: 'comment1',
      ellipsis: {
        showTitle: false,
      },
      render: (comment1) => (
        <Tooltip placement="topLeft" title={comment1}>
          {comment1}
        </Tooltip>
      ),
    },
    {  
      title: t('action'),  
      key: 'action',
      fixed:'right',
      render: (text, record) => (  
        <>  
           <Button type="link"  onClick={() => handleView(record)}>  
           {t('view')}  
          </Button> 
          {viewStatus ? null : (
            <>
              <Button type="link" onClick={() => handleEdit(record)}>  
              {t('edit')}  
              </Button>  
            </>
          )}
         
          {/* <Button type="link" danger onClick={() => handleDelete(record.id)}>  
          {t('delete')}   
          </Button>   */}
   
        </>  
      ),  
    },  
  ];


  const getData = async (formData) => {
    const { success, data} = await list({...formData, orderby: 'id', order: 0})
    if(!success) return false
    console.log(data)
    const list2 = data.data.page
    return {
      data: list2,
      total: data.data.total
    }
  } 

  const handleAdd = () =>{
    SetisView(false)
    form.resetFields()
    setTitle("新增/New")
    showModal()
  }

  const showModal = () => {  
    setIsModalVisible(true);  
  };  

  
  const handleOk = () => {  
    // 调用接口添加数据，这里假设你有一个函数addFormData来处理添加逻辑  
    // const response = addFormData(newFormData);  
    // ...处理接口响应...  
    const values = form.getFieldsValue();  
    if(Title=='新增/New'){
        //新增
        values.id =null
        add(values).then(res=>{
            message.success("Success")
            setOnReloadNum(Date.now())
             // 假设添加成功，关闭弹窗  
            setIsModalVisible(false);  
        }).catch(()=>{
           
        })
    }else{
        //修改
        edit(values).then(res=>{
            message.success("Success")
            setOnReloadNum(Date.now())
             // 假设添加成功，关闭弹窗  
            setIsModalVisible(false);  
        }).catch(()=>{
       })
    }

  
    // 根据需要更新formData或执行其他逻辑  
    // ...  
  };  

  const handleView = (record) =>{
   SetisView(true)
   setTitle("查看/View")
   console.log(record,'record')
   form.setFieldsValue({ ...record });  
   setIsModalVisible(true);  
  }

  const handleEdit = (record) =>{
    SetisView(false)
    setTitle("修改/Edit")
    console.log(record,'record')
    form.setFieldsValue({ ...record });  
    setIsModalVisible(true);  
    // 这里可以添加打开模态框并显示编辑表单的逻辑  
  }

  const handleDelete = (key) =>{
    let inciIds = []
    inciIds.push(key)
    Modal.confirm({  
      title: 'Confirm Delete',  
      content: 'Please confirm to DELETE SELECTED RECORDS!',  
      onOk() {  
        del(inciIds).then(res=>{
            message.success("Success")
            setOnReloadNum(Date.now())
        }) 
      },  
    }); 
  }
  
  const handleCancel = () => {  
    setIsModalVisible(false);  
  };  

  const renderOperator = <>
    <Button disabled={viewStatus} type="primary" size="small" onClick={handleAdd}>{t('add')}</Button>
  </>
  
  return (
    <div> 
    <MemoTable 
      name='basic'
      formColumns={formColumns}
      columns={columns as any}
      rowKey='id'
      operator={renderOperator}
      getData={getData}
      refreshKey={onReloadNum}
    />
    <Modal  
          title={Title}
          visible={isModalVisible}  
          onOk={handleOk}  
          onCancel={handleCancel}  
        >  
          <Form form={form} layout="vertical">
            <Form.Item  
                name="id"  
                label="id" 
                hidden 
            >  
                <Input disabled/>  
            </Form.Item> 
            {/* 这里假设添加的内容也是一个对象，包含key和value */}  
            <Form.Item  
              name="serial"  
              label={t('inci.serial')}
              rules={[{ required: true, message: '请输入序号！' }]}    
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="inciCn"  
              label={t('inci.inciCn')}  
              rules={[{ required: true, message: '请输入中文名称！' }]}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="inciUs"  
              label={t('inci.inciUs')}  
              rules={[{ required: true, message: '请输入英文名称！' }]} 
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="comment2"  
              label={t('inci.comment2')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="maxDoseLeaveon"  
              label={t('inci.maxDoseLeaveon')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>
            <Form.Item  
              name="maxDoseRinseoff"  
              label={t('inci.maxDoseRinseoff')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
            <Form.Item  
              name="comment1"  
              label={t('inci.comment1')}  
            >  
              <Input disabled={isView}/>  
            </Form.Item>  
          </Form>  
        </Modal>  
    </div>
  )
}
export default inciList
